package com.ponxu.mb.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.Global;
import com.ponxu.utils.Lang;

public class EncodingFilter implements Filter {
	private static final Log LOG = LogFactory.getLog();
	private String encoding = "UTF-8";

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		LOG.debug("----------EncodingFilter begin----------");

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);

		chain.doFilter(request, response);

		LOG.debug("----------EncodingFilter end----------");
	}

	public void init(FilterConfig fConfig) throws ServletException {
		String s = Global.read("ENCODING");
		if (Lang.isNotEmpty(s)) {
			encoding = s;
		}
	}

	public void destroy() {
	}

}
